package com.kitty.cross.core;

import com.kitty.cross.core.codec.CrossSerializerHelper;
import com.kitty.cross.core.server.BaseCMessageDispatcher;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.buffer.SimpleBufferAllocator;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.DefaultSocketSessionConfig;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.SocketSessionConfig;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
//后加
import com.kitty.cross.core.Game2GameIoHandler;
import com.kitty.cross.core.server.BaseCMessageDispatcher;
@Slf4j
public class CrossServer {
	

	private SocketAcceptor acceptor;

	/**
	 * start Mina serversocket
	 * @throws Exception
	 */
	public void start(int port) throws Exception {
		IoBuffer.setUseDirectBuffer(false);
		IoBuffer.setAllocator(new SimpleBufferAllocator());

		acceptor = new NioSocketAcceptor();
		acceptor.setReuseAddress(true);
		acceptor.getSessionConfig().setAll(getSessionConfig());

		log.info("cross server start at port:{},正在监听服务器点对点的连接...", port);
		DefaultIoFilterChainBuilder filterChain = acceptor.getFilterChain();
		filterChain.addLast("codec",
				new ProtocolCodecFilter(CrossSerializerHelper.getInstance().getCodecFactory()));
		//指定业务逻辑处理器
		acceptor.setHandler(new Game2GameIoHandler(BaseCMessageDispatcher.getInstance()));
		//设置端口号
		acceptor.setDefaultLocalAddress(new InetSocketAddress(port));
		//启动监听
		acceptor.bind();
	}

	private SocketSessionConfig getSessionConfig() {
		SocketSessionConfig config = new DefaultSocketSessionConfig();
		config.setKeepAlive(true);
		config.setReuseAddress(true);
		config.setSoLinger(0);

		return config;
	}

	public void shutdown() {
		if (acceptor != null) {
			acceptor.unbind();
			acceptor.dispose();
		}
		log.error("---------> cross server stop successfully");
	}

}
